import cv2

"""
opencv1 效果更好

"""
def opencv1():
    img = cv2.imread("../File/image1.jpg")

    ## Image to Gray Image
    gray_image = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

    ## Gray Image to Inverted Gray Image
    inverted_gray_image = 255 - gray_image

    ## Blurring The Inverted Gray Image
    blurred_inverted_gray_image = cv2.GaussianBlur(inverted_gray_image, (19, 19), 0)

    ## Inverting the blurred image
    inverted_blurred_image = 255 - blurred_inverted_gray_image

    ### Preparing Photo sketching
    sketck = cv2.divide(gray_image, inverted_blurred_image, scale=256.0)

    cv2.imwrite("../File/image1-opencv1.jpg", sketck)
    # cv2.imshow("Original Image", img)
    # cv2.imshow("Pencil Sketch", sketck)
    # cv2.waitKey(0)


def opencv2():
    # 读取图片
    img = cv2.imread("../File/image1.jpg")
    # 灰度
    grey = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
    invert = cv2.bitwise_not(grey)
    # 高斯滤波
    blur_img = cv2.GaussianBlur(invert, (7, 7), 0)
    inverse_blur = cv2.bitwise_not(blur_img)
    sketch_img = cv2.divide(grey, inverse_blur, scale=256.0)
    # 保存
    cv2.imwrite('../File/image1-opencv2.jpg', sketch_img)
    cv2.waitKey(0)

# 卡通化图片
def opencv3():
    image_path = '../File/image1.jpg'
    # 读取图像
    img = cv2.imread(image_path)
    if img is None:
        print("无法加载图像，请检查路径。")
        return

    # 将图像转换为灰度图
    gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

    # 应用中值滤波以减少噪声
    gray_filtered = cv2.medianBlur(gray, 7)

    # 使用自适应阈值处理得到边缘
    edges = cv2.adaptiveThreshold(
        gray_filtered, 255,
        cv2.ADAPTIVE_THRESH_MEAN_C,
        cv2.THRESH_BINARY,
        9,
        9
    )

    # 应用双边滤波以保留边缘并平滑颜色区域
    color = cv2.bilateralFilter(img, d=9, sigmaColor=75, sigmaSpace=75)

    # 将边缘与平滑后的图像融合
    cartoon = cv2.bitwise_and(color, color, mask=edges)

    # 保存结果
    output_path = "../File/image1-opencv3.jpg"
    cv2.imwrite(output_path, cartoon)
    print(f"卡通化图像已保存到: {output_path}")


def opencv4():
    # 输入和输出文件路径
    image_path = "../File/image1.jpg"  # 输入的图像路径
    output_path = "../File/image1-opencv4.jpg"  # 输出的素描化图像路径

    # 读取图片
    img = cv2.imread(image_path)
    if img is None:
        print("无法加载图片，请检查路径。")
        return

    # 将图片转换为灰度图
    gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

    # 反转灰度图像
    inverted = cv2.bitwise_not(gray)

    # 对反转图像进行高斯模糊
    blurred = cv2.GaussianBlur(inverted, (21, 21), sigmaX=0, sigmaY=0)

    # 反转模糊后的图像
    inverted_blurred = cv2.bitwise_not(blurred)

    # 生成素描效果
    sketch = cv2.divide(gray, inverted_blurred, scale=256.0)

    # 保存素描图
    cv2.imwrite(output_path, sketch)
    print(f"素描图片已保存到: {output_path}")

# opencv1()
# opencv2()
# opencv3()
opencv4()